package com.bawei.module_equipment.ui.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_equipment.R
import com.bawei.module_equipment.databinding.ItemDeviceBinding
import com.bawei.module_equipment.model.EquipmentModelItem

/**
 *作者：lxy
 *功能:
 *时间：2025/6/13
 */
class EquipmentAdapter(
    private val onItemClick: ((Int) -> Unit)? = null
) : RecyclerView.Adapter<EquipmentAdapter.EquipmentViewHolder>() {

    private val mData = mutableListOf<EquipmentModelItem>()

    fun setData(data: List<EquipmentModelItem>) {
        mData.clear()
        mData.addAll(data)
        val size = mData.size
        notifyItemRangeInserted(size - 1, data.size)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EquipmentViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.item_device, parent, false)
        return EquipmentViewHolder(view, onItemClick)
    }

    override fun getItemCount(): Int {
        return mData.size
    }

    override fun onBindViewHolder(holder: EquipmentViewHolder, position: Int) {
        val item = mData[position]
        holder.bind(item)  // 调用ViewHolder的bind方法绑定数据
    }

    inner class EquipmentViewHolder(
        itemView: View,
        private val onItemClick: ((Int) -> Unit)? = null
    ) : RecyclerView.ViewHolder(itemView) {

        private val binding: ItemDeviceBinding? = DataBindingUtil.bind(itemView)

        // 绑定数据到视图
        fun bind(item: EquipmentModelItem) {
            binding?.apply {
                // 直接使用数据绑定来设置数据
                deviceName.text = "项目名称/设备名称:${item.deviceName}"
                deviceType.text = "设备类型:${item.deviceType}"
                location.text = "安装地点:${item.installationLocation}"
                failureRate.text = "故障率:${item.failureRate}"
                statusText.text = "${item.status}"
            }


        }

        init {
            itemView.setOnClickListener {
                onItemClick?.invoke(adapterPosition)
            }
        }

    }
}